package com.talking.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadUtils;
import com.talking.App;
import com.talking.BuildConfig;
import com.talking.R;
import com.talking.adapter.ChatAdapter;
import com.talking.bean.ChatBean;
import com.talking.databinding.ActivityChatGroupBinding;
import com.talking.model.Http;
import com.talking.presenter.HistoryPresenter;
import com.talking.utils.Utils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ChatGroupActivity extends AppCompatActivity {
    private ActivityChatGroupBinding binding;
    private ChatAdapter adp;
    private final List<ChatBean> data=new ArrayList<>();
    private ActivityResultLauncher<Intent> launcher;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        binding= ActivityChatGroupBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        adp=new ChatAdapter(this,data);
        binding.chatGroupList.setAdapter(adp);

        binding.chatGroupEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals("")){
                    binding.chatGroupSendOrAdd.setImageResource(R.drawable.add);
                }else{
                    binding.chatGroupSendOrAdd.setImageResource(R.drawable.send);
                }
            }
        });
        binding.chatGroupEdit.setOnClickListener(v -> binding.chatGroupFunctions.setVisibility(View.GONE));
        binding.chatGroupSendFile.setOnClickListener(v -> {
            Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,false);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            launcher.launch(Intent.createChooser(intent,"请选择文件"));
            if (binding.chatGroupFunctions.getVisibility()==View.VISIBLE){
                binding.chatGroupFunctions.setVisibility(View.GONE);
            }
        });
        binding.chatGroupList.setOnItemClickListener((parent, view, position, id) -> {
            ChatBean bean = data.get(position);
            if (bean.content_type.equals("文件")) {
                File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/talking/");
                if (!f.exists()) f.mkdir();
                if (new File(f.getAbsolutePath() + "/" + new File(bean.ifFileUrl).getName()).exists()) {
                    fileClick(new File(f.getAbsolutePath() + "/" + new File(bean.ifFileUrl).getName()).getAbsolutePath());
                } else {
                    Utils.toast("正在下载");
                    FileDownloader.setup(this);
                    FileDownloader.getImpl().create(Http.BASE_URL + bean.ifFileUrl).setPath(FileDownloadUtils.getDefaultSaveRootPath()+File.separator+new File(bean.ifFileUrl).getName()).setListener(new FileDownloadListener() {
                        @SuppressLint("SetTextI18n")
                        @Override
                        protected void pending(BaseDownloadTask task, int progress, int totalBytes) {
                        }
                        @SuppressLint("SetTextI18n")
                        @Override
                        protected void connected(BaseDownloadTask task, String tag, boolean isContinue, int progress, int totalBytes) {
                        }

                        @Override
                        protected void progress(BaseDownloadTask task, int progress, int totalBytes){
                        }
                        @Override
                        protected void blockComplete(BaseDownloadTask task) {
                        }
                        @Override
                        protected void retry(final BaseDownloadTask errortask, final Throwable ex, final int retryingTimes, final int progress) {
                        }
                        @Override
                        protected void completed(BaseDownloadTask task) {
                            fileClick(FileDownloadUtils.getDefaultSaveRootPath()+File.separator+new File(bean.ifFileUrl).getName());
                        }
                        @Override
                        protected void paused(BaseDownloadTask task, int progress, int totalBytes) {
                        }
                        @Override
                        protected void error(BaseDownloadTask task, Throwable e) {
                            e.printStackTrace();
                        }
                        @Override
                        protected void warn(BaseDownloadTask task) {
                        }
                    }).start();
                }
            }
        });
        setTitle(App.groupBean.groupName);
        refresh();
        launcher=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode()==-1){
                HistoryPresenter.upload(new File(result.getData().getData().getPath()), new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        e.printStackTrace();
                    }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        String url = response.body().string();
                        HistoryPresenter.add("文件", "群组", App.sp.getString("account", ""), App.groupBean.id,url, new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                e.printStackTrace();
                            }
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) {
                                refresh();
                            }
                        });
                    }
                });
            }
            if (result.getResultCode()==4){
                finish();
            }
        });
    }
    private void refresh() {
        HistoryPresenter.query(App.sp.getString("account", ""), App.groupBean.id,"group", new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                runOnUiThread(() -> {
                    data.clear();
                    try {
                        JSONArray ja = new JSONObject(response.body().string()).getJSONArray("data");
                        for (int i = 0; i < ja.length(); i++) {
                            JSONObject jo = ja.getJSONObject(i);
                            if (jo.getString("content_type").equals("文件")){
                                String fileName = jo.getString("content");
                                data.add(new ChatBean(jo.getString("senderAccount"),"文件(点击查看) 文件名:"+fileName.substring(fileName.lastIndexOf("-")+1),jo.getString("createTime"),jo.getString("id"),jo.getString("content_type"),jo.getString("content")));
                            }else {
                                data.add(new ChatBean(jo.getString("senderAccount"),jo.getString("content"),jo.getString("createTime"),jo.getString("id"),jo.getString("content_type"),""));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    adp.notifyDataSetChanged();
                });
            }
        });
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (android.R.id.home==item.getItemId()){ finish(); }
        if (item.getItemId()== R.id.menu_groupmsg){
            launcher.launch(new Intent(ChatGroupActivity.this, GroupSettingActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_groupmsg, menu);
        return true;
    }
    public void group_expand(View view){
        if (binding.chatGroupEdit.getText().toString().equals("")){
            if (binding.chatGroupFunctions.getVisibility()==View.GONE){
                binding.chatGroupFunctions.setVisibility(View.VISIBLE);
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(binding.chatGroupEdit.getWindowToken(), 0);
            }else {
                binding.chatGroupFunctions.setVisibility(View.GONE);
                binding.chatGroupEdit.setShowSoftInputOnFocus(true);
            }
        }else {
            HistoryPresenter.add("文本", "群组", App.sp.getString("account", ""), App.groupBean.id, binding.chatGroupEdit.getText().toString(), new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) {
                    refresh();
                }
            });
            binding.chatGroupEdit.setText("");
        }
    }
    private void fileClick(String dir) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(ChatGroupActivity.this);
        dialog.setTitle("请选择").setItems(new CharSequence[]{"分享", "打开","删除"}, (dialog1, which) -> {
            File file = new File(dir);
            switch (which) {
                case 0:
                    Intent share = new Intent(Intent.ACTION_SEND);
                    String type = Utils.getMimeType(dir);
                    share.setType(type);
                    share.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        share.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(ChatGroupActivity.this, BuildConfig.APPLICATION_ID + ".fileprovider", file));
                        share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    } else {
                        share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
                    }
                    startActivity(Intent.createChooser(share, "分享到："));
                    break;
                case 1:
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        intent.setDataAndType(FileProvider.getUriForFile(ChatGroupActivity.this, BuildConfig.APPLICATION_ID + ".fileprovider", file), Utils.getMimeType(dir));
                    } else {
                        intent.setDataAndType(Uri.fromFile(file), Utils.getMimeType(dir));
                    }
                    startActivity(intent);
                    break;
                case 2:
                    if (file.exists())file.delete();
                    Utils.toast("已删除");
            }
        }).show();
    }
}